import React from 'react';
import type { TransactionRead, AccountRead } from '../types';
import XMarkIcon from './icons/XMarkIcon';

interface TransactionDetailModalProps {
  transaction: TransactionRead | null;
  onClose: () => void;
  onEdit: (transaction: TransactionRead) => void;
  onDelete: (id: string) => void;
  accountMap: Map<string, AccountRead>;
}

const DetailRow: React.FC<{ label: string; value: React.ReactNode; isAmount?: boolean }> = ({ label, value, isAmount = false }) => (
  <div className={`flex justify-between items-start py-3 border-b border-slate-700/50 ${isAmount ? 'text-lg' : 'text-sm'}`}>
    <span className="text-slate-400 flex-shrink-0 pr-4">{label}</span>
    <div className={`font-semibold text-right ${isAmount ? 'text-white' : 'text-slate-200'}`}>{value}</div>
  </div>
);

const TransactionDetailModal: React.FC<TransactionDetailModalProps> = ({ transaction, onClose, onEdit, onDelete, accountMap }) => {
  if (!transaction) return null;

  const split = transaction.attributes.transactions[0];
  const isExpense = split.type === 'withdrawal';

  const account = accountMap.get(split.source_id! ?? split.destination_id!);
  const currencySymbol = account?.attributes.currency_symbol ?? '$';
  const currencyCode = account?.attributes.currency_code ?? 'USD';

  const formattedAmount = new Intl.NumberFormat('zh-CN', { style: 'currency', currency: currencyCode }).format(parseFloat(split.amount));
  
  const handleDelete = () => {
    if(window.confirm('您确定要删除这笔交易吗？此操作无法撤销。')) {
      onDelete(transaction.id);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-end justify-center bg-black/60" onClick={onClose}>
      <div 
        className="w-full max-w-md bg-slate-800 rounded-t-3xl shadow-2xl p-6 flex flex-col transform transition-transform duration-300 ease-out translate-y-0"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-bold text-white">交易详情</h2>
          <button onClick={onClose} className="text-slate-400 hover:text-white">
            <XMarkIcon className="h-6 w-6" />
          </button>
        </div>
        
        <div className="flex-grow space-y-2">
            <DetailRow 
                label="金额" 
                value={<span className={isExpense ? 'text-red-400' : 'text-green-400'}>{isExpense ? '-' : '+'} {formattedAmount}</span>} 
                isAmount 
            />
            <DetailRow label="描述" value={split.description} />
            <DetailRow label="日期" value={new Date(split.date).toLocaleString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' })} />
            <DetailRow label="类型" value={<span className="capitalize">{split.type === 'withdrawal' ? '支出' : '收入'}</span>} />
            {split.category_name && <DetailRow label="分类" value={split.category_name} />}
            
            {split.tags && split.tags.length > 0 && (
              <DetailRow label="标签" value={
                  <div className="flex flex-wrap gap-x-2 gap-y-1 justify-end max-w-xs">
                      {split.tags.map(tag => (
                          <span key={tag} className="px-2 py-1 text-xs bg-slate-700 text-slate-300 rounded-full">{tag}</span>
                      ))}
                  </div>
              } />
            )}

            {isExpense ? (
                <>
                    <DetailRow label="从账户" value={split.source_name} />
                    <DetailRow label="至" value={split.destination_name} />
                </>
            ) : (
                <>
                    <DetailRow label="从" value={split.source_name} />
                    <DetailRow label="至账户" value={split.destination_name} />
                </>
            )}
        </div>
        <div className="mt-6 flex space-x-4">
            <button
                onClick={handleDelete}
                className="w-full bg-red-600/80 hover:bg-red-600/100 disabled:bg-slate-600 disabled:cursor-not-allowed text-white font-bold py-3 rounded-lg transition-colors flex justify-center items-center"
            >
                删除
            </button>
            <button
                onClick={() => onEdit(transaction)}
                className="w-full bg-cyan-600 hover:bg-cyan-500 disabled:bg-slate-600 disabled:cursor-not-allowed text-white font-bold py-3 rounded-lg transition-colors flex justify-center items-center"
            >
                编辑
            </button>
        </div>
      </div>
    </div>
  );
};

export default TransactionDetailModal;